package main

import (
	"flag"
	"log"
	"os"
	"os/signal"
	"strings"
	"syscall"

	"github.com/juexin/gin-base/internal/config"
	"github.com/juexin/gin-base/internal/model"
	"github.com/juexin/gin-base/internal/router"
	"github.com/juexin/gin-base/pkg/database"
)

func main() {
	// 命令行参数
	var migrate bool
	flag.BoolVar(&migrate, "migrate", false, "Run database migrations")
	flag.Parse()

	// 加载配置
	cfg := config.Load()

	// 初始化数据库
	db := database.Init(cfg.Database)

	// 运行迁移
	if migrate {
		if err := model.AutoMigrate(db); err != nil {
			log.Fatal("Failed to migrate database:", err)
		}
		log.Println("Database migration completed")
		return
	}

	// 自动迁移数据库
	if err := model.AutoMigrate(db); err != nil {
		log.Fatal("Failed to auto migrate database:", err)
	}

	// 设置路由
	r := router.Setup(db, cfg)

	// 优雅关闭
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		// 格式化端口地址
		port := cfg.Server.Port
		if !strings.HasPrefix(port, ":") {
			port = ":" + port
		}
		
		// 启动服务器
		log.Printf("Starting server on %s", port)
		if err := r.Run(port); err != nil {
			log.Fatal("Failed to start server:", err)
		}
	}()

	// 等待退出信号
	<-quit
	log.Println("Shutting down server...")
	log.Println("Server exited")
}
